package handler

import (
	"context"
	"gozeroStandalone/internal/logic"
	"gozeroStandalone/internal/types"
	"math"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
)

/*
 +----------------------------------------------------------------------
 + Title        : DemoHandler
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2025-10-18
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 案例处理器
 +----------------------------------------------------------------------
*/
type DemoHandler struct {
	BaseHandler
}

/**
 * 新增
 *
 * @param []string Hobby ---------------------------必传
 * @param map[string]string Spec -------------------必传
 * @return json
 * @author huwl
 * @date 2025/11/22 22:14:22
 */
func (control *DemoHandler) Add(w http.ResponseWriter, r *http.Request) {
	var req types.DemoAddRequest
	if err := httpx.Parse(r, &req); err != nil {
		httpx.Error(w, err)
		return
	}

	// 调用逻辑层
	demoLogic := logic.NewDemoLogicInstance(context.Background(), control.SvcCtx)
	err := demoLogic.Add(req)
	if err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(r, w, control.WithMessage("新增成功"))
}

/**
 * 编辑
 *
 * @param uint16 Id --------------------------------必传
 * @param []string Hobby ---------------------------非必传
 * @param map[string]string Spec -------------------非必传
 * @return json
 * @author huwl
 * @date 2025/11/22 22:14:22
 */
func (control *DemoHandler) Edit(w http.ResponseWriter, r *http.Request) {
	var req types.DemoEditRequest
	if err := httpx.Parse(r, &req); err != nil {
		httpx.Error(w, err)
		return
	}

	// 调用逻辑层
	demoLogic := logic.NewDemoLogicInstance(context.Background(), control.SvcCtx)
	err := demoLogic.Edit(req)
	if err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(r, w, control.WithMessage("编辑成功"))
}

func (control *DemoHandler) List(w http.ResponseWriter, r *http.Request) {
	var req types.DemoQueryRequest
	if err := httpx.Parse(r, &req); err != nil {
		httpx.Error(w, err)
		return
	}

	page := req.Page
	pageSize := req.PageSize
	if req.Page <= 0 {
		page = 1
	}
	if req.PageSize <= 0 {
		pageSize = 10
	}

	// 调用逻辑层
	demoLogic := logic.NewDemoLogicInstance(context.Background(), control.SvcCtx)
	result, total, err := demoLogic.List(req, page, int8(pageSize))
	if err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(r, w, control.WithData(map[string]interface{}{
		"page":       page,
		"page_size":  pageSize,
		"total":      total,
		"page_total": math.Ceil(float64(total) / float64(pageSize)),
		"result":     result,
	}))
}
